package com.neusoft.elmboot.controller;

import com.neusoft.elmboot.po.User;
import com.neusoft.elmboot.service.UserService;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/UserController")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/getUserByIdByPass")
    public ResponseEntity<Map<String, Object>> getUserByIdByPass(@RequestBody User user) throws Exception {
        User foundUser = userService.getUserByIdByPass(user);
        Map<String, Object> response = new HashMap<>();

        if (foundUser != null) {
            response.put("success", true);
            response.put("message", "登录成功");
            response.put("data", foundUser); // 可选，如果前端需要用户数据
            return ResponseEntity.ok(response); // 返回 200 OK
        } else {
            response.put("success", false);
            response.put("message", "用户不存在或密码错误");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); // 返回 400 Bad Request
        }
    }

    @RequestMapping("/getUserById")
    public User getUserById(User user) throws Exception {
        return userService.getUserById(user.getUserId());
    }

    @PostMapping("/saveUser")
    public Map<String, Object> saveUser(@RequestBody User user) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 保存用户并获取返回的 userId
            int result = userService.saveUser(user);

            // 如果保存成功，返回 success 和 userId
            if (result > 0) {
                response.put("success", true);
            } else {
                // 保存失败，返回失败信息
                response.put("success", false);
            }
        } catch (Exception e) {
            // 捕获异常并返回失败状态
            response.put("success", false);
            response.put("error", e.getMessage());
            e.printStackTrace(); // 打印异常详细信息，方便调试
        }
        return response;
    }

    @RequestMapping("/updateUserById")
    public int updateUserById(User user) throws Exception {
        return userService.updateUserById(user);
    }

    @RequestMapping("/removeUser")
    public int removeUser(User user) throws Exception {
        return userService.removeUser(user);
    }

}
